/*
 *所有关于cw_djlc_configuration_tradition类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*cw_djlc_configuration_traditionService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using VOL.Core.BaseProvider;
using VOL.Core.Extensions.AutofacManager;
using VOL.Entity.DomainModels;
using System.Linq;
using VOL.Core.Utilities;
using System.Linq.Expressions;
using VOL.Core.Extensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using VOL.Finance.IRepositories;
using System.Collections.Generic;
using VOL.Core.DBManager;
using System;

namespace VOL.Finance.Services
{
    public partial class cw_djlc_configuration_traditionService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly Icw_djlc_configuration_traditionRepository _repository;//访问数据库

        [ActivatorUtilitiesConstructor]
        public cw_djlc_configuration_traditionService(
            Icw_djlc_configuration_traditionRepository dbRepository,
            IHttpContextAccessor httpContextAccessor
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }

        WebResponseContent webResponse = new WebResponseContent();

        public override PageGridData<cw_djlc_configuration_tradition> GetPageData(PageDataOptions options)
        {
            QueryRelativeExpression = (IQueryable<cw_djlc_configuration_tradition> queryable) =>
            {
                queryable = queryable.Where(x => x.del_flag == "0");
                return queryable;
            };
            return base.GetPageData(options);
        }

        /*public override WebResponseContent Import_Configuration(List<IFormFile> files, string id)
        {
            return base.ImportConfigurationTradition(files, id);
        }*/

        public override WebResponseContent Del(object[] keys, bool delList = true)
        {
            //配置表在删除操作时，如果发现该配置表全删除没有数据了，需要同步更新定价流程主表is_have_disposition = 0
            var djlcId = "1";
            DelOnExecuting = (object[] _keys) =>
            {
                if (_keys != null)
                {
                    cw_djlc_configuration_tradition tradition = DBServerProvider.DbContext.Set<cw_djlc_configuration_tradition>().Where(c => c.cw_djlc_configuration_tradition_id == Guid.Parse(_keys[0].ToString())).ToList().FirstOrDefault();
                    djlcId = tradition != null ? tradition.cw_djlc_djzb_id.ToString() : "";
                }
                return webResponse.OK();
            };
            DelOnExecuted = (object[] _keys) =>
            {
                List<cw_djlc_configuration_tradition> list = DBServerProvider.DbContext.Set<cw_djlc_configuration_tradition>().Where(c => c.cw_djlc_djzb_id == Guid.Parse(djlcId)).ToList();
                if (list == null || list.Count == 0)
                {
                    cw_djlc_djzb djzb = DBServerProvider.DbContext.Set<cw_djlc_djzb>().Where(c => c.cw_djlc_djzb_id == Guid.Parse(djlcId)).ToList().FirstOrDefault();
                    if (djzb != null)
                    {
                        djzb.is_have_disposition = 0;
                        DBServerProvider.DbContext.Update(djzb);
                        DBServerProvider.DbContext.SaveChanges();
                    }
                }
                return webResponse.OK();
            };
            return base.Del(keys, delList);
        }
        public virtual WebResponseContent Import_Configuration(List<IFormFile> files, string id)
        {
            
            ImportOnExecuting = (List<cw_djlc_configuration_tradition> list) =>
            {
                if (list.Count<2)
                {
                    return webResponse.Error("配置表最少上传两条，请重新上传！");
                }
                var dapper = DBServerProvider.SqlDapper;
                try
                {
                    //逻辑删除 之前上传的数据
                    //string sql = "update cw_djlc_configuration_tradition set del_flag = 1 where cw_djlc_djzb_id = @value ";
                    //string sql = "delete from cw_djlc_configuration_tradition where cw_djlc_djzb_id = @value ";
                    //var data = dapper.ExcuteNonQuery(sql, new { value = id });

                    //定价流程主表 配置项类型更新 1传统车 2新能源车
                    string sql2 = "update cw_djlc_djzb set configuration_type = 1 , is_have_disposition = 1 where cw_djlc_djzb_id = @value ";
                    var data2 = dapper.ExcuteNonQuery(sql2, new { value = id });

                    cw_djlc_djzb djzb = DBServerProvider.DbContext.Set<cw_djlc_djzb>().Where(c => c.cw_djlc_djzb_id == Guid.Parse(id) ).ToList().LastOrDefault();
                    string newmaterialnum = djzb.newmaterialnum;//需求物料号
                    foreach (cw_djlc_configuration_tradition item in list)
                    {
                        if (!string.IsNullOrEmpty(newmaterialnum)&&!string.IsNullOrEmpty(item.new_materialnum)&&newmaterialnum.Equals(item.new_materialnum))
                        {
                            djzb.vehicletype = item.vehicle_model;//车型
                            djzb.drivetype = item.driving_form;//驱动形式
                            djzb.fuel = item.fuel_type;//燃料
                            djzb.pilothouse = item.cage;//驾驶室
                            djzb.enginetype = item.ct_engine_type; //发动机型号
                            djzb.transmissiontype = item.transmission_model;//变速器型号
                            djzb.sale_keyword = djzb.salechannel + item.cage + item.fuel_type + item.vehicle_model + item.driving_form; //销售关键词
                            djzb.serialnum = item.serial_number;
                            //根据配置表的相关信息去财务主表去匹配财务变动取值信息，如果匹配到就将该财务主表uuid更新到定价流程主表；
                            cw_djlc_cwzb cwzb = DBServerProvider.DbContext.Set<cw_djlc_cwzb>().Where(c => c.salechannel.Contains(djzb.salechannel) && item.cage.Contains(c.pilothouse) && c.fuel.Contains(item.fuel_type) && c.vehicletype.Contains(item.vehicle_model) && c.drivetype.Contains(item.driving_form)).ToList().LastOrDefault();
                            if (cwzb != null)
                            {
                                djzb.cw_djlc_cwzb_id = cwzb.cw_djlc_cwzb_id;
                            }

                            //根据配置表的车型以及燃料类型和产品定价的销售渠道三个信息去判断：
                            //1、如果是危险品牵引车 直接3%
                            if ("经销".Equals(djzb.salechannel))
                            {
                                //危险品牵引车 边际率3%
                                if (!string.IsNullOrEmpty(item.vehicle_model) && item.vehicle_model.Contains("危险品牵引车"))
                                {
                                    djzb.marginalrate = 3;
                                }
                                else//柴油:1%, CNG:3%, LNG:3%
                                {
                                    if (!string.IsNullOrEmpty(item.fuel_type))
                                    {
                                        if (item.fuel_type.Contains("柴油"))
                                        {
                                            djzb.marginalrate = 1;
                                        }
                                        else if (item.fuel_type.Contains("CNG") || item.fuel_type.Contains("LNG"))
                                        {
                                            djzb.marginalrate = 3;
                                        }
                                    }
                                }
                            }
                            DBServerProvider.DbContext.Update(djzb);
                            DBServerProvider.DbContext.SaveChanges();
                        }
                    }
                    dapper.Commit();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    dapper.Rollback();
                }          
                return webResponse.OK();
            };
            return base.ImportConfigurationTradition(files, id);
        }


    }
}
